<template>
  <!-- 轮播图 开始 -->
  <div class="swiper">
    <el-carousel
      ref="carousel"
      class="el_carousel"
      indicator-position="none"
      arrow="never"
      @change="changeCarousel"
    >
      <el-carousel-item
        class="el_carousel_item"
        v-for="(item, index) in imageList"
        :key="`carousel_${index}`"
      >
        <!-- <img :src="item.url" class="img" alt=""> -->
        <li-image :src="item" class="img" :lazy-load="false" />
      </el-carousel-item>
    </el-carousel>
    <div class="scroll_wrapper" ref="scrollBox" v-if="showDot">
      <div class="small_list">
        <div
          class="small_img"
          :ref="`smallImg_${index}`"
          :class="carouselIndex == index ? 'active' : ''"
          v-for="(item, index) in imageList"
          :key="`small_img_${index}`"
          @click="chooseCarousel(index)"
        >
          <li-image :src="item" class="img" />
        </div>
      </div>
    </div>
  </div>
  <!-- 轮播图 end -->
</template>
<script>
import { Carousel, CarouselItem } from "element-ui";
import BScroll from "better-scroll";
export default {
  name: "UserCarousel",
  components: {
    [Carousel.name]: Carousel,
    [CarouselItem.name]: CarouselItem,
  },
  props: {
    list: {
      type: Array,
      default: function () {
        return [];
      },
    },
    showDot: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    list: {
      handler: function (n) {
        this.imageList = n || [];
      },
      immediate: true,
    },
  },
  data() {
    return {
      imageList: [],
      carouselIndex: 0,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    // 初始化滚动
    init() {
      let _this = this;
      let _dom = this.$refs.scrollBox;
      if (_dom) {
        let bs = new BScroll(this.$refs.scrollBox, {
          scrollX: true,
          probeType: 3,
          click: true,
        });
        const hooks = bs.scroller.hooks;
        hooks.on("scrollToElement", (el, pos) => {});
        this.scrollBox = bs;
      }
    },

    // 监听轮播图切换
    changeCarousel(e) {
      this.carouselIndex = e;
      this.scrollToDom();
    },

    // 手动切换轮播图
    chooseCarousel(e) {
      this.carouselIndex = e;
      this.$refs.carousel.setActiveItem(e);
      this.scrollToDom();
    },

    // 滚动到某个元素
    scrollToDom() {
      let scrollBox = this.scrollBox;
      let id = `smallImg_${this.carouselIndex}`;
      let o = this.$refs[id]
      if (o) {
        let _dom = o[0];
        scrollBox.scrollToElement(_dom, 500, true);
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import "./index.less";
</style>